<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "miniprogram_session".
 *
 * @property string $sid
 * @property string $openid
 * @property string $unionid
 * @property string $session_key
 * @property int $ctime
 * @property string $session_data
 */
class MiniprogramSession extends \yii\db\ActiveRecord
{
    const LOGIN_URL = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';

    static public function login($appid, $code){
        $wxAccount = WxAccountMini::getObjByAppid($appid);
        if(!$wxAccount) throw new \Exception('appid 不存在', 1);
        $url = sprintf(self::LOGIN_URL, $wxAccount->app_id, $wxAccount->app_secret,$code);
        $res = file_get_contents($url);
        Yii::error($code.':'.$res);
//        print_r($res);exit;
        if(!$res) throw new \Exception('小程序登录接口返回空', 1);
        $arr = json_decode($res, 1);
        if(!$arr) throw new \Exception('小程序登录接口返回格式错误：'.$res, 1);
        if(isset($arr['errcode']) && $arr['errcode'] > 0) throw new \Exception('小程序登录接口返回错误：'.$res, 1);

        $obj = self::findOne(['sid'=>$code]);
        if(!$obj){
            $obj = new self();
            $obj->sid=$code;
        }
        $obj->openid=$arr['openid'];
        $obj->unionid=@$arr['unionid'];
        $obj->session_key=$arr['session_key'];
        $obj->ctime=time();
        $obj->session_data='';
        if(!$obj->save())throw new \Exception(json_encode($obj->getErrors(),JSON_UNESCAPED_UNICODE), 1);
        return $obj;
    }
    static public function getObjBySid($sid){
        return self::findOne(['sid'=>$sid]);
    }
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'miniprogram_session';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['sid', 'openid', 'session_key', 'ctime'], 'required'],
            [['ctime'], 'integer'],
            [['session_data'], 'string'],
            [['sid', 'session_key'], 'string', 'max' => 255],
            [['openid', 'unionid'], 'string', 'max' => 64],
            [['sid'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'sid' => 'Sid',
            'openid' => 'Openid',
            'unionid' => 'Unionid',
            'session_key' => 'Session Key',
            'ctime' => 'Ctime',
            'session_data' => 'Session Data',
        ];
    }
}
